package com.cn.controller;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: chenyuncong
 * @Date: 2019/11/22 11:27
 */
@RestController
@RefreshScope
public class IndexController {

    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @NacosInjected
    private ConfigService configService;

    @GetMapping("getUseLocalCache")
    public String getUseLocalCache(){
        //数据可以在nacos配置中心把数据推过来
        return useLocalCache+"";
    }

    @GetMapping("testPublishConfig")
    public void testPublishConfig() throws NacosException {
        configService.publishConfig("serviceConsumerConfig2", "groupConfig2", "9527");
    }

    @NacosConfigListener(dataId = "serviceConsumerConfig2",groupId = "groupConfig2")
    public void onMessage2(String config) {
        System.out.println(config);
    }

    @NacosConfigListener(dataId = "serviceConsumerConfig",groupId = "groupConfig")
    public void onMessage(String config) {
        System.out.println(config);
    }

    @RequestMapping(value = {"/","index"})
    public Map<String,String> index() throws UnknownHostException {
        return new HashMap<String,String>(){{
            this.put("name","admin");
            this.put("sex","男");
            this.put("address",InetAddress.getLocalHost().getHostAddress());
        }};
    }


}
